#include "frame.h"
#include "serial.h"
#include "video.h"
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/poll.h>

extern int serial_fd;
SerialConfig serial_config = {
    .baud_rate = B115200,
    .parity = 'N',
    .data_bits = 8,
    .stop_bits = 1
};

void print_usage(const char *prog_name) {
    printf("Usage: %s <serial_device>\n", prog_name);
    printf("Example: %s /dev/ttyUSB0\n", prog_name);
}

extern void handle_user_input();
void process_received_data(const uint8_t *data, size_t length) {
    // Implement received data processing logic
    printf("Received data: %.*s\n", (int)length, data);
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        print_usage(argv[0]);
        return 1;
    }

    serial_fd = serial_open(argv[1], &serial_config);
    if (serial_fd < 0) return 1;

    fcntl(serial_fd, F_SETFL, fcntl(serial_fd, F_GETFL) | O_NONBLOCK);

    struct pollfd fds[2] = {
        { .fd = STDIN_FILENO, .events = POLLIN },
        { .fd = serial_fd, .events = POLLIN }
    };

    printf("Serial communication program started, waiting for data...\n");

    while (1) {
        if (poll(fds, 2, 100) > 0) {
            if (fds[0].revents & POLLIN) {
                handle_user_input();
            }
            
            if (fds[1].revents & POLLIN) {
                uint8_t buffer[256];
                ssize_t bytes_read = serial_read(serial_fd, buffer, sizeof(buffer));
                if (bytes_read > 0) {
                    process_received_data(buffer, bytes_read);
                }
            }
        }
    }

    serial_close(serial_fd);
    return 0;
}